package com.my.netty.thread;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.my.netty.NettyPoolClient;
import com.my.netty.util.Const;
import io.netty.channel.Channel;
import io.netty.channel.pool.SimpleChannelPool;
import io.netty.util.concurrent.Future;

import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

/**
 * Author: chenzhen
 * Description:
 * Date:    2019/10/27 7:27
 */
public class DataService implements Runnable {

    @Override
    public void run() {
        do {
            try {
                List<Entity> configBackList = Db.use().query("select * from fu_sys_task_log where status is null limit 100");

                if (configBackList != null && !configBackList.isEmpty()) {
                    String ids = configBackList.stream().map(data -> data.getStr("id")).collect(Collectors.joining(", ", "(", ")"));
                    configBackList.forEach(val -> {
                        val.set("table", "fu_sys_task_log");
                    });
                    JSONConfig jsonConfig = new JSONConfig();
                    jsonConfig.setIgnoreNullValue(false);
                    jsonConfig.setDateFormat("yyyy-MM-dd hh:mm:ss");
                    configBackList = (List<Entity>) JSONUtil.wrap(configBackList, jsonConfig);
                    String transData = JSONUtil.toJsonStr(configBackList);
                    final SimpleChannelPool pool = NettyPoolClient.poolMap.get(Const.remoteAddr);
                    Future<Channel> f = pool.acquire();
                    Channel channel = f.get(60, TimeUnit.SECONDS);
                    System.out.println("send msesssage:" + transData);
                    channel.writeAndFlush(transData + "\r\n");
                    pool.release(channel);
                    Db.use().execute("update fu_sys_task_log set status = 1 where id in "+ ids);
                } else {
                    TimeUnit.SECONDS.sleep(10);
                }

            } catch (SQLException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            } finally {
            }
        } while (true);

    }
}
